<!-- 天然气 -->
<template>
  <div class="flex-center table-top">
    <px-form ref="formRef" :model="queryParams" :inline="true" class="custom-form-ui search-form">
      <px-form-item label="日期" prop="date">
        <px-date-picker
          v-model="queryParams.date"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="YYYY-MM-DD"
        />
      </px-form-item>
      <div class="search-form-btn">
        <px-button type="primary" @click="handleQuery">搜索</px-button>
        <px-button @click="resetQuery">重置</px-button>
      </div>
    </px-form>
  </div>
  <div class="table-top-btn-container">
    <px-button v-has="'ALL_ENEYGY_DATA_ADD'" type="primary" @click="handleAdd">新增</px-button>
    <px-button v-has="'ALL_ENEYGY_DATA_UPLOAD'" type="primary" plain @click="handleDownloadTemplate">下载模板</px-button>
    <px-upload action="#" :http-request="handleImport" :show-file-list="false" accept=".xlsx, xls" style="margin: 0 16px">
      <px-button v-has="'ALL_ENEYGY_DATA_UPLOAD'" type="primary" plain>批量导入</px-button>
    </px-upload>
    <px-button v-has="'ALL_ENEYGY_DATA_DELETE'" plain @click="handleBatchDelete">删除</px-button>
  </div>
  <div v-loading="tableLoading" class="table-content">
    <px-table height="calc(100vh - 370px)" :data="tableData" size="small" border class="common-table" @selection-change="tableSelect">
      <px-table-column type="selection" fixed width="55" prop="selection" align="center" />
      <px-table-column type="index" label="序号" fixed width="55" align="center" />
      <px-table-column prop="meterReadingDate" label="日期" min-width="120" show-overflow-tooltip />
      <px-table-column prop="toal" label="合计消耗量(m³)" min-width="120" show-overflow-tooltip />
      <px-table-column prop="epiPower" label="EPI消耗量(m³)" min-width="120" show-overflow-tooltip />
      <px-table-column prop="voc1Power" label="VOC1消耗量(m³)" min-width="120" show-overflow-tooltip />
      <px-table-column prop="voc2Power" label="VOC2消耗量(m³)" min-width="120" show-overflow-tooltip />
      <px-table-column prop="pmdPower" label="PMD消耗量(m³)" min-width="120" show-overflow-tooltip />
      <px-table-column label="操作" width="100" fixed="right" align="center">
        <template #default="scope">
          <px-tooltip content="编辑" placement="top">
            <px-button v-has="'ALL_ENEYGY_DATA_EDIT'" link icon="EditPen" type="primary" @click="handleEdit(scope.row)" />
          </px-tooltip>
          <px-tooltip content="删除" placement="top">
            <px-button v-has="'ALL_ENEYGY_DATA_DELETE'" link icon="Delete" type="danger" @click="handleDelete(scope.row)" />
          </px-tooltip>
        </template>
      </px-table-column>
    </px-table>
    <pagination
      v-show="total > 0"
      v-model:page="pageNum"
      v-model:limit="pageSize"
      class="table-pagination"
      :total="total"
      @pagination="handleQuery"
    />
  </div>

  <!-- 新增/编辑弹窗 -->
  <px-dialog v-model="editDialogVisible" :title="handleType === 'ADD' ? '新增' : '编辑'" width="510" @close="cancelEdit">
    <px-form ref="editFormRef" :model="editFormParams" :rules="rules" label-width="150px">
      <px-form-item label="日期" prop="date">
        <px-date-picker
          v-model="editFormParams.date"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择"
          :disabled="handleType === 'EDIT'"
          style="width: 300px"
        />
      </px-form-item>
      <px-form-item label="EPI消耗量(m³)" prop="epiPower">
        <px-input-number
          v-model="editFormParams.epiPower"
          :precision="2"
          :min="0.01"
          :max="9999"
          placeholder="请输入"
          style="width: 300px"
          clearable
        />
      </px-form-item>
      <px-form-item label="VOC1消耗量(m³)" prop="voc1Power">
        <px-input-number
          v-model="editFormParams.voc1Power"
          :precision="2"
          :min="0.01"
          :max="9999"
          placeholder="请输入"
          style="width: 300px"
          clearable
        />
      </px-form-item>
      <px-form-item label="VOC2消耗量(m³)" prop="voc2Power">
        <px-input-number
          v-model="editFormParams.voc2Power"
          :precision="2"
          :min="0.01"
          :max="9999"
          placeholder="请输入"
          style="width: 300px"
          clearable
        />
      </px-form-item>
      <px-form-item label="PMD消耗量(m³)" prop="pmdPower">
        <px-input-number
          v-model="editFormParams.pmdPower"
          :precision="2"
          :min="0.01"
          :max="9999"
          placeholder="请输入"
          style="width: 300px"
          clearable
        />
      </px-form-item>
      <px-form-item label="合计消耗量(m³)" prop="sumVal">
        <px-input-number v-model="sumVal" :precision="2" disabled clearable style="width: 300px" />
      </px-form-item>
    </px-form>
    <template #footer>
      <span class="dialog-footer">
        <px-button @click="cancelEdit">取消</px-button>
        <px-button type="primary" @click="saveEdit">确定</px-button>
      </span>
    </template>
  </px-dialog>

  <!-- 导入失败提示弹窗 -->
  <px-dialog v-model="uploadErrorVisible" title="导入失败" width="800">
    <ul class="error-list">
      <li v-for="item in uploadErrorList" :key="item">
        {{ item }}
      </li>
    </ul>
  </px-dialog>
</template>

<script setup>
import { ref, reactive, toRefs, onMounted, computed } from "vue";
import { getNaturalGasListAPI, saveNaturalGasAPI, deleteNaturalGasAPI, uploadNaturalGasAPI } from "@/api/modules/energy";
import { PxMessage, PxMessageBox } from "px-ui";

defineOptions({
  name: "ALL_ENERGY_DATA_NATURALGAS"
});

const formRef = ref(null);
const editFormRef = ref(null);

const state = reactive({
  queryParams: {
    date: ""
  },
  tableLoading: false,
  tableData: [],
  total: 0,
  pageNum: 1,
  pageSize: 20,
  handleType: "ADD",
  editDialogVisible: false,
  rowData: {},
  editFormParams: {
    date: "",
    epiPower: null,
    voc1Power: null,
    voc2Power: null,
    pmdPower: null
  },
  tableSelectedData: [],
  uploadErrorVisible: false,
  uploadErrorList: []
});
const {
  queryParams,
  tableLoading,
  tableData,
  total,
  pageNum,
  pageSize,
  handleType,
  editDialogVisible,
  editFormParams,
  uploadErrorVisible,
  uploadErrorList
} = toRefs(state);

const rules = computed(() => ({
  date: [{ required: true, message: "日期不能为空", trigger: "change" }],
  epiPower: [{ required: true, message: "EPI消耗量不能为空", trigger: "blur" }],
  voc1Power: [{ required: true, message: "VOC1消耗量不能为空", trigger: "blur" }],
  voc2Power: [{ required: true, message: "VOC2消耗量不能为空", trigger: "blur" }],
  pmdPower: [{ required: true, message: "PMD消耗量不能为空", trigger: "blur" }]
}));

onMounted(() => {
  handleQuery();
});

const tableSelect = val => {
  state.tableSelectedData = val;
};

let sumVal = computed(() => {
  const { epiPower, voc1Power, voc2Power, pmdPower } = state.editFormParams;
  return epiPower + voc1Power + voc2Power + pmdPower;
});

// 查询
const handleQuery = async () => {
  try {
    state.tableLoading = true;
    const { date } = state.queryParams;
    const params = {
      pageNum: state.pageNum,
      pageSize: state.pageSize,
      dataTimeStart: date === "" || date === null ? "" : date[0],
      dataTimeEnd: date === "" || date === null ? "" : date[1]
    };
    const res = await getNaturalGasListAPI(params);
    state.total = res.total;
    state.tableData = res.data;
  } catch (err) {
    console.log(err);
  } finally {
    state.tableLoading = false;
  }
};

// 重置
const resetQuery = () => {
  formRef.value.resetFields();
  handleQuery();
};

// 新增
const handleAdd = () => {
  state.handleType = "ADD";
  state.editDialogVisible = true;
  state.editFormParams = {
    date: "",
    epiPower: null,
    voc1Power: null,
    voc2Power: null,
    pmdPower: null
  };
};

// 下载模板
const handleDownloadTemplate = () => {
  const fileUrl = "/models/燃气能耗量模板.xlsx";

  // 创建一个隐藏的a标签
  const link = document.createElement("a");
  link.href = fileUrl;

  // 将a标签添加到DOM并触发点击事件
  document.body.appendChild(link);
  link.click();

  // 移除a标签
  document.body.removeChild(link);
};

// 导入
const handleImport = async options => {
  try {
    const { file } = options;
    const formData = new FormData();
    formData.append("file", file);
    const res = await uploadNaturalGasAPI(formData);
    if (res.length > 0) {
      state.uploadErrorList = res.split("#");
      state.uploadErrorVisible = true;
    } else {
      PxMessage.success("批量导入成功");
    }
    handleQuery();
  } catch (error) {
    console.log(error);
  }
};

// 编辑
const handleEdit = row => {
  state.handleType = "EDIT";
  state.editDialogVisible = true;
  state.rowData = row;
  state.editFormParams = {
    date: row.meterReadingDate,
    epiPower: Number(row.epiPower),
    voc1Power: Number(row.voc1Power),
    voc2Power: Number(row.voc2Power),
    pmdPower: Number(row.pmdPower)
  };
  sumVal.value = Number(row.meterReadingDate) + Number(row.epiPower) + Number(row.voc1Power) + Number(row.voc2Power) + Number(row.pmdPower);
};

// 取消编辑
const cancelEdit = () => {
  editFormRef.value.resetFields();
  state.editDialogVisible = false;
};

// 保存编辑
const saveEdit = async () => {
  editFormRef.value.validate(async validate => {
    if (validate) {
      const { date, epiPower, voc1Power, voc2Power, pmdPower } = state.editFormParams;
      const params = {
        id: state.handleType === "EDIT" ? state.rowData.id : null,
        meterReadingDate: date,
        toal: sumVal.value,
        epiPower,
        voc1Power,
        voc2Power,
        pmdPower
      };
      const res = await saveNaturalGasAPI(params);
      if (res.length > 0) {
        PxMessage.error(res);
      } else {
        cancelEdit();
        handleQuery();
        PxMessage.success(`${state.handleType === "EDIT" ? "修改" : "新增"}成功`);
      }
    }
  });
};

// 批量删除
const handleBatchDelete = () => {
  if (state.tableSelectedData.length === 0) {
    PxMessage.error("请选择要删除的数据");
    return;
  }
  const params = {
    id: state.tableSelectedData.map(item => item.id)
  };
  sureDelete(params);
};

// 删除
const handleDelete = row => {
  const params = {
    id: [row.id]
  };
  sureDelete(params);
};

const sureDelete = async params => {
  PxMessageBox.confirm("是否确认删除？", "温馨提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(async () => {
      const res = await deleteNaturalGasAPI(params);
      if (res.length > 0) {
        PxMessage.error(res);
      } else {
        PxMessage.success("删除成功");
        handleQuery();
      }
    })
    .catch(() => {});
};
</script>

<style lang="scss" scoped>
@import url("@/views/common/energy/energyData/scss/common.scss");
</style>
